package com.controller;

import com.entry.Financing;
import com.entry.Instituty;
import com.entry.User;
import com.entry.Voucher;
import com.google.gson.Gson;
import com.pojo.*;
import com.service.FinancingService;
import com.service.InstitutyService;
import com.service.UserService;
import com.service.VoucherService;
import com.service.impl.FinancingServiceImpl;
import com.service.impl.InstitutyServiceImpl;
import com.service.impl.UserServiceImpl;
import com.service.impl.VoucherServiceImpl;
import com.util.PageHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

@WebServlet("/FMS/*")
public class Servlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    FinancingService financing = new FinancingServiceImpl();
    private FinancingService financingService = new FinancingServiceImpl();
    private InstitutyService institutyService = new InstitutyServiceImpl();


    private VoucherService voucherService=new VoucherServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获得请求路径
        String url = request.getRequestURI();
        String methodName = url.substring(url.lastIndexOf("/") + 1);
        Class cla = Servlet.class;
        try {
            Method method = cla.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(cla.newInstance(), request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户信息
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        //System.out.println("接收到的账号和密码是：" + account + "..." + password);
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        ArrayList<User> str = userService.selectUser(user);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(str));
    }
    public void queryFinancing(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        //获取企业id
        FinIns finIns = new FinIns();
        String enterprise_id = request.getParameter("enterprise_id");
        finIns.setEnterprise_id(Integer.parseInt(enterprise_id));
        String no = request.getParameter("no");
        String ins = request.getParameter("instituty_name");
        String max = request.getParameter("Max");
        String min = request.getParameter("Min");
        String create_time = request.getParameter("create_time");
        String status = request.getParameter("status");
//        System.out.println("获取到的编号是"+no+",获取到的机构下拉值是"+ins+",获取到的金额最大值是"+max+",获取到的金额最小值是"+min+",获取到的开单时间是"+create_time+",获取到的处理状态是"+status);
        if(no!=null){
            finIns.setNo(no);
        }
        String a = "中国工商银行";
        String b = "中国农业银行";
        if(ins!=null && !ins.trim().isEmpty()){
            if("a".equals(ins)){
                finIns.setName(a);
            }else if("b".equals(ins)){
                finIns.setName(b);
            }
        }
        int Max=0;
        int Min=0;
        if(max!=null && !max.trim().isEmpty()){
            Max = Integer.parseInt(max);
        }
        if(min!=null && !min.trim().isEmpty()){
            Min = Integer.parseInt(min);
        }
        if(create_time != null && !create_time.trim().isEmpty()){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            finIns.setCreate_time(dateFormat.parse(create_time));
        }
        if(status != null && !status.trim().isEmpty()){
            if("成功".equals(status)){
                finIns.setStatus("A");
            }else if("融资中".equals(status)){
                finIns.setStatus("B");
            }
            else if("失败".equals(status)){
                finIns.setStatus("C");
            }
        }
        //设置分页---当前页indexPage、总页数countPage
        PageHelper pageHelper = new PageHelper();
        String indexPage = request.getParameter("indexPage");
        if (indexPage != null && !indexPage.trim().isEmpty() && !indexPage.equalsIgnoreCase("null")) {
            pageHelper.setIndexPage(Integer.parseInt(indexPage));
//            System.out.println("接收到的当前页标是"+pageHelper.getIndexPage());
        }
        pageHelper.setCountData(financingService.selectQuerySize(finIns,pageHelper,Max,Min));
        if (pageHelper.getCountData() <= 4) {
            pageHelper.setIndexPage(1);
        }
        ArrayList<FinIns> list1 = financingService.selectQuery(finIns, pageHelper, Max, Min);
        pageHelper.setList(list1);
        //System.out.println("最终获取到的数据是"+pageHelper.getList());
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(pageHelper));//传递给前台分页工具类
    }

    public void queryInstituties(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SimpleDateFormat slf=new SimpleDateFormat();
        // 实现查询所有机构并转发到 text.jsp 的逻辑
        ArrayList<Instituty> instituties = institutyService.selectAll();
        String no = request.getParameter("no");
        String val = request.getParameter("val");
        Voucher voucher=new Voucher();
        voucher.setNo(no);
        VouEntIns vouEntIns = new VouEntIns();
        //System.out.println("传回来的no是"+no);

        ArrayList<VouEntIns> list= voucherService.selectQueryByNo(no);
        ArrayList<SelectFinAndIns> list1=productMoney(request,response);
        //System.out.println("voucher list是"+list);
        //System.out.println("Financing list1是"+list1);
        ABC abc = new ABC();
        abc.setVou(list);
        abc.setSelfin(list1);
        Gson gson = new Gson();
//        System.out.println(abc.getVou());
        response.getWriter().println(gson.toJson(abc));
    }


    public void queryDetail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        FinIns finIns = new FinIns();
        String no = request.getParameter("no");

        finIns.setNo(no);
        FinIns finIns2 = financingService.selectQuery(finIns);
        if (finIns2.getStatus().equals("A")) {
            finIns2.setStatus("成功");
        } else {
            finIns2.setStatus("失败");
        }
        if (finIns2.getFin().equals("A")) {
            finIns2.setFin("已放款");
        } else {
            finIns2.setFin("未放款");
        }
        finIns2.setPayment_interest_type(finIns2.getPayment_interest_type());
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(finIns2));
    }

    public void queryMyTicket(HttpServletRequest request, HttpServletResponse response) throws IOException {
        VouInsEnt vouInsEnt = new VouInsEnt();
        PageHelper pageHelper = new PageHelper();
        int Max = 0;
        int Min = 0;
        String eid = request.getParameter("eid");
        vouInsEnt.setEnterprise_id(Integer.parseInt(eid));
        String no = request.getParameter("no");
        String enterprise_name = request.getParameter("enterprise_name");
        String open_enterprise_name = request.getParameter("open_enterprise_name");
        String max = request.getParameter("Max");
        String min = request.getParameter("Min");
        String indexPage = request.getParameter("indexPage");
//        System.out.println("获取到的编号是"+no+",获取到的收单企业是"+enterprise_name+",获取到的开单企业是"+max+",获取到的开单日期是"+min+",获取到的最小金额是"+Min+",获取到的最大金额是"+Max);
        if(no!=null&& !no.trim().isEmpty()){
            vouInsEnt.setNo(no);
        }
        if(enterprise_name!=null && !enterprise_name.trim().isEmpty()){

            if("a".equals(enterprise_name)){
                vouInsEnt.setEnterprise_name("阿里科技有限公司");
            }else if("b".equals(enterprise_name)){
                vouInsEnt.setEnterprise_name("腾讯科技有限公司");
            }else if("c".equals(enterprise_name)){
                vouInsEnt.setEnterprise_name("百度科技有限公司");
            }else if("d".equals(enterprise_name)){
                vouInsEnt.setEnterprise_name("隆基股份有限公司");
            }else if("e".equals(enterprise_name)){
                vouInsEnt.setEnterprise_name("京东集团");
            }
        }
        if(open_enterprise_name!=null && !open_enterprise_name.trim().isEmpty()){
            if("a".equals(open_enterprise_name)){
                vouInsEnt.setOpen_enterprise_name("阿里科技有限公司");
            }else if("b".equals(open_enterprise_name)){
                vouInsEnt.setOpen_enterprise_name("腾讯科技有限公司");
            }else if("c".equals(open_enterprise_name)){
                vouInsEnt.setOpen_enterprise_name("百度科技有限公司");
            }else if("d".equals(open_enterprise_name)){
                vouInsEnt.setOpen_enterprise_name("隆基股份有限公司");
            }else if("e".equals(open_enterprise_name)){
                vouInsEnt.setOpen_enterprise_name("京东集团");
            }
        }
        if(max!=null && !max.trim().isEmpty()){
            Max = Integer.parseInt(max);
        }
        if(min!=null && !min.trim().isEmpty()){
            Min = Integer.parseInt(min);
        }
        if (indexPage != null && !indexPage.trim().isEmpty() && !indexPage.equalsIgnoreCase("null")) {
            pageHelper.setIndexPage(Integer.parseInt(indexPage));
//            System.out.println("接收到的当前页标是"+pageHelper.getIndexPage());
        }
        pageHelper.setCountData(voucherService.selectQuerySize(vouInsEnt,Max,Min));
        if (pageHelper.getCountData() <= 4) {
            pageHelper.setIndexPage(1);
        }
        ArrayList<VouInsEntUser> list = voucherService.selectQuery(vouInsEnt,pageHelper,Max,Min);
        pageHelper.setList(list);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(pageHelper));
    }
    public void queryMyTicketDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        VouInsEntUser vouInsEntUser=new VouInsEntUser();
        String no = request.getParameter("no");
        vouInsEntUser.setNo(no);
        ArrayList list=voucherService.selectQuery(vouInsEntUser);
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(list));

    }

    public ArrayList<SelectFinAndIns> productMoney(HttpServletRequest request, HttpServletResponse response){
        ArrayList<SelectFinAndIns> list1=new ArrayList<>();
        SelectFinAndIns selectFinAndIns=new SelectFinAndIns();
        String mon = request.getParameter("val");

        double money = 0;
        if(mon!=null &&!mon.trim().isEmpty()){
            money = Double.parseDouble(mon);
        }
        String remark;
        ArrayList<Instituty> list=institutyService.selectAll();
        for (int i = 0; i <list.size() ; i++) {
            double interest= list.get(i).getInterest();
            double cost=money*interest;
            double receipt_amount=money-cost;
            selectFinAndIns=new SelectFinAndIns();
            selectFinAndIns.setName(list.get(i).getName());
            selectFinAndIns.setReceipt_amount(receipt_amount);
            selectFinAndIns.setCost(cost);
            selectFinAndIns.setInterest(interest);
            selectFinAndIns.setReceipt_day(list.get(i).getReceipt_day());
//            System.out.println(selectFinAndIns);
            list1.add(selectFinAndIns);
        }
        return list1;
    }

    public void addTwoList(HttpServletRequest request, HttpServletResponse response){
        String instituty_name = request.getParameter("bank");
        String interest = request.getParameter("num");
        String no=request.getParameter("no");
        int n=0;
//        System.out.println("添加用到的no是"+no);
        ArrayList<SelectFinAndIns> selectFinAndIns= productMoney(request,response);
        for (int i = 0; i <selectFinAndIns.size() ; i++) {
            if(selectFinAndIns.get(i).getName().equals(instituty_name)){
                n=i;
            }
        }
        SelectFinAndIns slfai=selectFinAndIns.get(n);
        double amount=slfai.getReceipt_amount()+slfai.getCost();

        ArrayList<Financing> financings=financingService.selectByNo(no);
        Financing financing0=financings.get(0);
//        System.out.println("之前的instituty是"+financing0);
        Financing financing=new Financing();
        Instituty instituty = new Instituty();
        instituty.setName(instituty_name);
        financing.setInstituty_id((institutyService.selectQuery(instituty).get(0).getInstituty_id()));
//        System.out.println("修改后的那什么id"+financing.getInstituty_id());
        financing.setAmount(amount);
        financing.setCost(slfai.getCost());
//        financing.setReceipt_amount(slfai.getReceipt_amount());
  //      financing.setInstituty_id(financing0.getInstituty_id());
//        financing.setUplink_address(financing0.getUplink_address());
        financing.setStatus("A");
        financing.setNo(no);
//        financing.setFin(financing0.getFin());
//        financing.setPayment_interest_type(financing0.getPayment_interest_type());
//        financing.setRemark(financing0.getRemark());
        //System.out.println("financing 表的添加内容为"+financing);
        financingService.insertFinancing(financing);



        ArrayList<Voucher> vouchers=voucherService.selectAllByNo(no);
//        System.out.println(vouchers);
        Voucher voucher0=vouchers.get(0);
        Voucher voucher=new Voucher();
        voucher.setNo(no);
        voucher.setAmount(amount);
        voucher.setEnterprise_id(voucher0.getEnterprise_id());
        voucher.setOpen_enterprise_id(voucher0.getOpen_enterprise_id());
        voucher.setInstituty_id(voucher0.getInstituty_id());
        voucher.setUplink_address(voucher0.getUplink_address());
        voucher.setStatus("B");
        voucher.setSource("融资留存");
        voucher.setSource_id(voucher0.getSource_id());
        voucher.setPayment_interest_type(voucher0.getPayment_interest_type());
        //System.out.println(""+voucher);
        voucherService.insertVoucher(voucher);
        int j = voucherService.updateVou(voucher);
//        System.out.println("修改状态的返回值vocher表"+j);


    }
}
